package com.hexinfo.dmpro.sparing.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置
 * 
 * @author
 *
 */

@Configuration
@EnableAsync
@Slf4j
public class ThreadPoolConfig {

	@Value("${thread.pool.threadNamePrefix}")
	private String threadNamePrefix;

	@Value("${thread.pool.queueCapacity}")
	private int queueCapacity;

	@Value("${thread.pool.corePoolSize}")
	private int corePoolSize;
 
	@Value("${thread.pool.maxPoolSize}")
	private int maxPoolSize;
 
	@Value("${thread.pool.keepAliveSeconds}")
	private int keepAliveSeconds;

	@Value("${thread.pool.rejectedExecutionHandler}")
	private String rejectedExecutionHandler;

	@Bean(name = "threadPoolTaskExecutor")
	public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
		log.info("线程池初始化开始");
		ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
		pool.setThreadNamePrefix(threadNamePrefix); //线程前缀
		pool.setQueueCapacity(queueCapacity); // 队列容量
		pool.setCorePoolSize(corePoolSize); // 核心线程池数
		pool.setMaxPoolSize(maxPoolSize); // 最大线程
		pool.setKeepAliveSeconds(keepAliveSeconds); //线程空闲时间
		pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()); // 队列满，线程被拒绝执行策略

		//通过反射获取RejectedExecutionHandlerClass 的类模板
		//Class<?> rejectedExecutionHandlerClass = Class.forName(rejectedExecutionHandler);
		//获取RejectedExecutionHandlerClass类的实例
		//RejectedExecutionHandler rejectedExecutionHandler = (RejectedExecutionHandler) rejectedExecutionHandlerClass.newInstance();
		//执行初始化
		pool.initialize();
		return pool;
	}

	@Value("${thread.pool.tableBackup.threadNamePrefix}")
	private String tbThreadNamePrefix;
	@Value("${thread.pool.tableBackup.queueCapacity}")
	private int tbQueueCapacity;
	@Value("${thread.pool.tableBackup.corePoolSize}")
	private int tbCorePoolSize;
	@Value("${thread.pool.tableBackup.maxPoolSize}")
	private int tbMaxPoolSize;
	@Value("${thread.pool.tableBackup.keepAliveSeconds}")
	private int tbKeepAliveSeconds;
	@Value("${thread.pool.tableBackup.rejectedExecutionHandler}")
	private String tbRejectedExecutionHandler;

	@Bean(name = "tableBackupThreadPool")
	public ThreadPoolTaskExecutor getPutThreadPool() {
		log.info("----------------表级热备线程池初始化开始");
		ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
		pool.setThreadNamePrefix(tbThreadNamePrefix); //线程前缀
		pool.setQueueCapacity(tbQueueCapacity); // 队列容量
		pool.setCorePoolSize(tbCorePoolSize); // 核心线程池数
		pool.setMaxPoolSize(tbMaxPoolSize); // 最大线程
		pool.setKeepAliveSeconds(tbKeepAliveSeconds); //线程空闲时间
		pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()); // 队列满，线程被拒绝执行策略
		//执行初始化
		pool.initialize();
		return pool;
	}
 
}